package com.hkts.naturalgas.curvesettings.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.naturalgas.curvesettings.entity.Curve;
import com.hkts.naturalgas.curvesettings.entity.CurveSettings;
import com.hkts.naturalgas.curvesettings.entity.CurveStateParamVo;
import com.hkts.naturalgas.curvesettings.entity.HktsCycleTime;
import com.hkts.naturalgas.curvesettings.mapper.CurveMapper;
import com.hkts.naturalgas.curvesettings.mapper.HktsCycleTimeMapper;
import com.hkts.naturalgas.curvesettings.service.ICurveService;
import com.hkts.naturalgas.curvesettings.service.ICurveSettingsService;
import com.hkts.naturalgas.datahandler.constance.EnviromentConstance;
import com.hkts.naturalgas.datahandler.constance.EnviromentCurveStateConstance;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentTemperature;
import com.hkts.naturalgas.dictionaries.mapper.HktsEnvironmentTemperatureMapper;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentTemperatureService;
import com.hkts.naturalgas.utils.Result;
import com.hkts.naturalgas.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2021-10-11
 */
@Service
@Transactional
@Slf4j
public class CurveServiceImpl extends ServiceImpl<CurveMapper, Curve> implements ICurveService {

    /* @Autowired
     public CurveConfig curveConfig;*/
    @Autowired
    private CurveMapper curveMapper;
    @Autowired
    public ICurveSettingsService iCurveSettingsService;
    @Autowired
    private HktsCycleTimeMapper hktsCycleTimeMapper;
    @Autowired
    private HktsEnvironmentTemperatureMapper hktsEnvironmentTemperatureMapper;
    @Autowired
    public IHktsEnvironmentTemperatureService iHktsEnvironmentTemperatureService;

    @Override
    public IPage<Curve> selectPage(Page<Curve> page, Curve curve) {
        QueryWrapper<Curve> query = Wrappers.query();
        QueryWrapper<Curve> entityWrapper = getEntityWrapper(query, curve);
        return curveMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<Curve> selectList(Curve curve) {
        QueryWrapper<Curve> query = Wrappers.query();
        QueryWrapper<Curve> entityWrapper = getEntityWrapper(query, curve);
        return curveMapper.selectList(entityWrapper);
    }

    @Override
    public Map<String, Curve> selectMap() {
        QueryWrapper<Curve> query = Wrappers.query();
        List<Curve> curves = curveMapper.selectList(query);
        Map<String, Curve> collect = curves.stream().collect(Collectors.toMap(Curve::getId, Function.identity()));
        return collect;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<Curve> getEntityWrapper(QueryWrapper<Curve> entityWrapper, Curve curve) {
        //条件拼接
        if (StringUtils.isNotBlank(curve.getCurveName())) {
            entityWrapper.like(Curve.CURVE_NAME, curve.getCurveName());
        }
        if (StringUtils.isNotBlank(curve.getWorkShopId())) {
            entityWrapper.like(Curve.WORK_SHOP_ID, curve.getWorkShopId());
        }
        return entityWrapper;
    }

    /**
     * 功能描述:
     * 配置初始化时间点
     *
     * @return: void
     * @Author: 杨春科
     * @Date: 2021-10-17 16:10
     * @Description //TODO
     */
    @Override
    public Result<Object> configuretimePoint(CurveStateParamVo curveState) {
        log.info("曲线时间点配置开始");
        QueryWrapper<Curve> query = Wrappers.query();
        query.lambda().eq(Curve::getWorkShopId, curveState.getWorkShopId());
        query.lambda().eq(Curve::getType, EnviromentConstance.IS_PY);
        query.lambda().orderByAsc(Curve::getFlameSystem);
        query.lambda().orderByAsc(Curve::getOrderBy);
        List<Curve> curve2 = curveMapper.selectList(query);
        QueryWrapper<HktsCycleTime> queryHktsCycleTime = Wrappers.query();
        queryHktsCycleTime.lambda().eq(HktsCycleTime::getWorkShopId,curveState.getWorkShopId());
        HktsCycleTime hktsCycleTime = hktsCycleTimeMapper.selectOne(queryHktsCycleTime);
        List<CurveSettings> totalCurveSettings=new ArrayList<>();
        //查询周期时间
        if(curveState.getFluctuationTime()>(hktsCycleTime.getCycleTime()/2)){
            return ResultUtil.error("偏移时间需要小于曲线时间的一半！");
        }
        //排烟架
        for (int j = 0; j < curve2.size(); j++) {
            Float fluctuationTime= curveState.getFluctuationTime()*j*3600;
            curve2.get(j).setIsBegin(EnviromentCurveStateConstance.IS_BEGIN);
            CurveSettings ve = new CurveSettings();
            ve.setCurveId(curve2.get(j).getId());
            List<CurveSettings> curveSettings = iCurveSettingsService.selectListforShelder(ve);
            float maxTime = 0;
            boolean index1 = true;
            for (int g = 0; g < curveSettings.size(); g++) {
                if(curveSettings.get(g).getIsHidden().equals("0")){
                    maxTime=curveSettings.get(g).getTimePoint();
                }
                curveSettings.get(g).setCurrentSeconds(0);
                curveSettings.get(g).setCurrentNode("0");
                if(index1){
                    if(curveSettings.get(g).getTotalSeconds()<fluctuationTime){
                        fluctuationTime=fluctuationTime- curveSettings.get(g).getTotalSeconds();
                    }else{
                        curveSettings.get(g).setCurrentSeconds(fluctuationTime.intValue());
                        curveSettings.get(g).setCurrentNode("1");
                        index1 = false;
                    }
                }
            }
            if(maxTime!=hktsCycleTime.getCycleTime()){
                return ResultUtil.error("温度曲线设置不一致，设置完成后再启动！");
            }
            //iCurveSettingsService.updateBatchById(curveSettings);
            totalCurveSettings.addAll(curveSettings);
        }
        iCurveSettingsService.updateBatchById(totalCurveSettings);
        this.updateBatchById(curve2);
        query.clear();
        query.lambda().eq(Curve::getWorkShopId, curveState.getWorkShopId());
        query.lambda().eq(Curve::getType, EnviromentConstance.IS_RS);
        query.lambda().orderByAsc(Curve::getFlameSystem);
        query.lambda().orderByAsc(Curve::getOrderBy);
        List<Curve> curves = curveMapper.selectList(query);
//燃烧架
        for (int j = 0; j < curves.size(); j++) {
            Float fluctuationTime=  curveState.getFluctuationTime()*(j/3)*3600;
            //计算时间波动量
            curves.get(j).setIsBegin(EnviromentCurveStateConstance.IS_BEGIN);
            CurveSettings ve = new CurveSettings();
            ve.setCurveId(curves.get(j).getId());
            List<CurveSettings> curveSettings = iCurveSettingsService.selectListforShelder(ve);
            Integer totalSeconds = 0;
            boolean index0 = false;
            boolean index1 = false;
            boolean index2 = false;
            for (int g = 0; g < curveSettings.size(); g++) {
                totalSeconds = totalSeconds + curveSettings.get(g).getTotalSeconds();
                if (j % 3 == 0) {
                    if (index0 == false && totalSeconds >= fluctuationTime) {
                        Float time = +fluctuationTime;
                        curveSettings.get(g).setCurrentSeconds(curveSettings.get(g).getTotalSeconds() - (totalSeconds - time.intValue()));
                        curveSettings.get(g).setCurrentNode("1");
                        index0 = true;
                    } else {
                        curveSettings.get(g).setCurrentNode("0");
                        curveSettings.get(g).setCurrentSeconds(0);
                    }
                } else if (j % 3 == 1) {
                    if (index1 == false && totalSeconds >= hktsCycleTime.getCycleTime() * 3600+fluctuationTime) {
                        Float time = hktsCycleTime.getCycleTime() * 3600+fluctuationTime;
                        curveSettings.get(g).setCurrentSeconds(curveSettings.get(g).getTotalSeconds() - (totalSeconds - time.intValue()));
                        curveSettings.get(g).setCurrentNode("1");
                        index1 = true;
                    } else {
                        curveSettings.get(g).setCurrentSeconds(0);
                        curveSettings.get(g).setCurrentNode("0");
                    }
                } else if (j % 3 == 2) {
                    if (index2 == false && totalSeconds >= hktsCycleTime.getCycleTime() * 3600 * 2+fluctuationTime) {
                        Float time = hktsCycleTime.getCycleTime() * 3600 * 2+fluctuationTime;
                        curveSettings.get(g).setCurrentSeconds(curveSettings.get(g).getTotalSeconds() - (totalSeconds - time.intValue()));
                        curveSettings.get(g).setCurrentNode("1");
                        index2 = true;
                    } else {
                        curveSettings.get(g).setCurrentSeconds(0);
                        curveSettings.get(g).setCurrentNode("0");
                    }
                }
            }
            iCurveSettingsService.updateBatchById(curveSettings);
        }
        this.updateBatchById(curves);
        log.info("曲线时间点配置结束");
        return ResultUtil.success("正在启动！");
    }

    @Override
    public void updateHeadNum(Map<String, Object> map) {
        log.info("炉号信息正在更新。。。");
       /* QueryWrapper<Curve> query = Wrappers.query();
        List<Curve> curves = curveMapper.selectList(query);
        for(int i=0;i<curves.size();i++){
            if(curves.get(i).getHeatNumberField()==null){
                continue;
            }
            if(map.get(curves.get(i).getHeatNumberField())!=null){
                Float v = Float.parseFloat(map.get(curves.get(i).getHeatNumberField()).toString());
                curves.get(i).setHeatNumber(v.intValue()+"");
            }else{
                log.info(curves.get(i).getCurveName()+"炉号为空");
            }
        }
        this.updateBatchById(curves);*/
        //炉号更新部分重写
        QueryWrapper<HktsEnvironmentTemperature> query = Wrappers.query();
        List<HktsEnvironmentTemperature> hktsEnvironmentTemperatures = hktsEnvironmentTemperatureMapper.selectList(query);
        for (int i = 0; i < hktsEnvironmentTemperatures.size(); i++) {
            //炉号
            if (map.get(hktsEnvironmentTemperatures.get(i).getHeatNumberName()) != null) {
                hktsEnvironmentTemperatures.get(i).setHeatNumber(map.get(hktsEnvironmentTemperatures.get(i).getHeatNumberName()).toString());
            }
            if (hktsEnvironmentTemperatures.get(i).getCycleTimeFiled() == null) {
                continue;
            }
            //周期
        /*    if(map.get(hktsEnvironmentTemperatures.get(i).getCycleTimeFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setCycleTime(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getCycleTimeFiled()).toString()));
            }*/
            //设定温度
            if(map.get(hktsEnvironmentTemperatures.get(i).getSettingTemperatureFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setSettingTemperature(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getSettingTemperatureFiled()).toString()));
            }
            //运行时间小时
            if(map.get(hktsEnvironmentTemperatures.get(i).getRunTimeHourFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setRunTimeHour(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getRunTimeHourFiled()).toString()));
            }
            //运行时间分钟
            if(map.get(hktsEnvironmentTemperatures.get(i).getRunTimeMinuteFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setRunTimeMinute(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getRunTimeMinuteFiled()).toString()));
            }
            //剩余时间小时
            if(map.get(hktsEnvironmentTemperatures.get(i).getRemainingTimeHourFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setRemainingTimeHour(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getRemainingTimeHourFiled()).toString()));
            }
            //剩余时间分钟
            if(map.get(hktsEnvironmentTemperatures.get(i).getRemainingTimeMinuteFiled())!= null){
                hktsEnvironmentTemperatures.get(i).setRemainingTimeMinute(Float.parseFloat(map.get(hktsEnvironmentTemperatures.get(i).getRemainingTimeMinuteFiled()).toString()));
            }
        }
        iHktsEnvironmentTemperatureService.updateBatchById(hktsEnvironmentTemperatures);
        log.info("炉号信息更新完成。。。");
    }
}
